import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 需求分析界面组件
class RequirementAnalysisWidget extends ConsumerStatefulWidget {
  final String? initialRequirement;
  final Function(Map<String, dynamic>)? onAnalysisComplete;

  const RequirementAnalysisWidget({
    super.key,
    this.initialRequirement,
    this.onAnalysisComplete,
  });

  @override
  ConsumerState<RequirementAnalysisWidget> createState() =>
      _RequirementAnalysisWidgetState();
}

class _RequirementAnalysisWidgetState
    extends ConsumerState<RequirementAnalysisWidget> {
  final TextEditingController _requirementController = TextEditingController();
  bool _isAnalyzing = false;
  AnalysisResult? _result;

  @override
  void initState() {
    super.initState();
    if (widget.initialRequirement != null) {
      _requirementController.text = widget.initialRequirement!;
    }
  }

  @override
  void dispose() {
    _requirementController.dispose();
    super.dispose();
  }

  /// 开始分析
  Future<void> _startAnalysis() async {
    if (_requirementController.text.trim().isEmpty) return;

    setState(() {
      _isAnalyzing = true;
      _result = null;
    });

    try {
      // 模拟AI分析
      await Future.delayed(const Duration(seconds: 2));

      // 检查widget是否仍然在树中
      if (!mounted) return;

      setState(() {
        _result = AnalysisResult.mock();
        _isAnalyzing = false;
      });

      if (widget.onAnalysisComplete != null) {
        widget.onAnalysisComplete!(_result!.toJson());
      }
    } catch (e) {
      // 检查widget是否仍然在树中
      if (!mounted) return;

      setState(() {
        _isAnalyzing = false;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: SelectableText('分析失败: ${e.toString()}')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 输入区域
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Icon(Icons.analytics, color: Colors.blue),
                    const SizedBox(width: 8),
                    SelectableText(
                      'AI需求分析',
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: _requirementController,
                  decoration: const InputDecoration(
                    labelText: '需求描述',
                    hintText: '请输入您的需求描述，AI将为您进行智能分析...',
                    border: OutlineInputBorder(),
                  ),
                  maxLines: 6,
                ),
                const SizedBox(height: 16),
                Row(
                  children: [
                    ElevatedButton.icon(
                      onPressed: _isAnalyzing ? null : _startAnalysis,
                      icon: _isAnalyzing
                          ? const SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Icon(Icons.auto_awesome),
                      label: SelectableText(_isAnalyzing ? '分析中...' : '开始分析'),
                    ),
                    const SizedBox(width: 12),
                    OutlinedButton(
                      onPressed: () => _requirementController.clear(),
                      child: const SelectableText('清空'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),

        const SizedBox(height: 16),

        // 分析结果
        if (_result != null) _buildAnalysisResult(_result!),
      ],
    );
  }

  /// 构建分析结果
  Widget _buildAnalysisResult(AnalysisResult result) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.insights, color: Colors.green),
                const SizedBox(width: 8),
                SelectableText(
                  '需求分析结果',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                Chip(
                  label: SelectableText('置信度: ${result.confidence}%'),
                  backgroundColor: Colors.green.shade100,
                ),
              ],
            ),
            const SizedBox(height: 16),
            SelectableText(
              '根据您的需求描述，AI分析结果如下：',
              style: const TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 16),

            // 功能点
            _buildSection('核心功能点', result.functionPoints, Icons.check_circle),

            // 技术建议
            _buildSection('技术建议', result.technicalSuggestions, Icons.lightbulb),

            // 风险提醒
            _buildSection('风险提醒', result.risks, Icons.warning),

            const SizedBox(height: 16),

            // 操作按钮
            Row(
              children: [
                ElevatedButton.icon(
                  onPressed: () {
                    // TODO: 生成文档
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: SelectableText('生成文档功能开发中...')),
                    );
                  },
                  icon: const Icon(Icons.description),
                  label: const SelectableText('生成文档'),
                ),
                const SizedBox(width: 12),
                OutlinedButton.icon(
                  onPressed: () {
                    // TODO: 创建任务
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: SelectableText('创建任务功能开发中...')),
                    );
                  },
                  icon: const Icon(Icons.add_task),
                  label: const SelectableText('创建任务'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建分析结果部分
  Widget _buildSection(String title, List<String> items, IconData icon) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Icon(icon, size: 16, color: Colors.grey.shade600),
            const SizedBox(width: 8),
            Text(
              title,
              style: const TextStyle(
                fontWeight: FontWeight.w500,
                fontSize: 16,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        ...items.map((item) => Padding(
              padding: const EdgeInsets.only(left: 24, bottom: 4),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('• ', style: TextStyle(color: Colors.grey.shade600)),
                  Expanded(child: SelectableText(item)),
                ],
              ),
            )),
        const SizedBox(height: 16),
      ],
    );
  }
}

/// 分析结果数据模型
class AnalysisResult {
  final List<String> functionPoints;
  final List<String> technicalSuggestions;
  final List<String> risks;
  final int confidence;

  const AnalysisResult({
    required this.functionPoints,
    required this.technicalSuggestions,
    required this.risks,
    required this.confidence,
  });

  Map<String, dynamic> toJson() {
    return {
      'functionPoints': functionPoints,
      'technicalSuggestions': technicalSuggestions,
      'risks': risks,
      'confidence': confidence,
    };
  }

  static AnalysisResult mock() {
    return const AnalysisResult(
      functionPoints: [
        '用户认证与权限管理',
        'Excel文件上传与解析',
        '任务管理与分配',
        '实时协作功能',
        'AI智能辅助',
      ],
      technicalSuggestions: [
        '建议使用Spring Boot + Flutter架构',
        '数据库推荐PostgreSQL',
        '实时通信使用WebSocket',
        '文件存储考虑云存储方案',
        'AI服务集成通义千问API',
      ],
      risks: [
        '大文件上传可能影响性能',
        '实时协作的并发冲突处理',
        'AI服务的稳定性依赖',
        '用户权限设计的复杂性',
      ],
      confidence: 92,
    );
  }
}
